<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-left">
        <view class="nav-back" @click="navigateBack">返回</view>
      </view>
      <view class="nav-title">附近回收点</view>
      <view class="nav-right">
        <view class="nav-location" @click="getLocation">定位</view>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-bar">
      <input type="text" v-model="searchKeyword" placeholder="搜索回收点名称或地址" class="search-input" />
    </view>

    <!-- 筛选分类 -->
    <view class="filter-tabs">
      <scroll-view scroll-x="true" class="filter-scroll">
        <view class="filter-tab" v-for="(filter, index) in filterCategories" :key="index" 
              :class="{ 'active': currentFilter === index }" @click="switchFilter(index)">
          <view class="filter-icon">{{ filter.icon }}</view>
          <view class="filter-text">{{ filter.name }}</view>
        </view>
      </scroll-view>
    </view>

    <!-- 地图容器 -->
    <view class="map-container">
      <map :latitude="latitude" :longitude="longitude" :markers="markers" 
           :show-location="showLocation" :include-points="mapPoints" 
           class="map" @markertap="onMarkerTap" @callouttap="onCalloutTap"></map>
    </view>

    <!-- 附近回收点列表 -->
    <view class="location-list">
      <view class="list-header">
        <view class="list-title">附近回收点 ({{ filteredLocations.length }})</view>
        <view class="list-filter" @click="showFilterOptions">
          <text>筛选</text>
          <text class="filter-icon">▼</text>
        </view>
      </view>
      
      <view class="location-items">
        <view class="location-item" v-for="(location, index) in filteredLocations" :key="index" 
              @click="showLocationDetail(location)">
          <view class="location-img">
            <image :src="location.image" mode="aspectFill"></image>
          </view>
          <view class="location-info">
            <view class="location-name">{{ location.name }}</view>
            <view class="location-category">
              <text class="category-tag" v-for="category in location.categories" :key="category">
                {{ category }}
              </text>
            </view>
            <view class="location-meta">
              <view class="location-address">{{ location.address }}</view>
              <view class="location-distance">{{ location.distance }}</view>
            </view>
            <view class="location-ratings">
              <text class="star-icon" v-for="n in 5" :key="n" :class="{ 'filled': n <= location.rating }">{{ '★' }}</text>
              <text class="rating-text">{{ location.rating }}</text>
              <text class="review-count">({{ location.reviews }}条评价)</text>
            </view>
            <view class="location-hours">
              <text class="hours-label">营业时间:</text>
              <text class="hours-text">{{ location.businessHours }}</text>
            </view>
          </view>
          <view class="location-actions">
            <button class="btn-call" @click.stop="callRecyclePoint(location.phone)">拨打</button>
            <button class="btn-navigate" @click.stop="navigateToLocation(location)">导航</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 筛选选项弹窗 -->
    <view class="modal-overlay" v-if="showFilterModal" @click="closeFilterModal">
      <view class="modal-content filter-modal" @click.stop>
        <view class="modal-header">
          <view class="modal-title">筛选条件</view>
          <view class="modal-close" @click="closeFilterModal">×</view>
        </view>
        <view class="modal-body">
          <view class="filter-section">
            <view class="filter-section-title">回收类型</view>
            <view class="filter-options">
              <view class="filter-option" v-for="(type, index) in recycleTypes" :key="index" 
                    :class="{ 'selected': selectedTypes.includes(index) }" @click="toggleType(index)">
                <view class="option-checkbox"></view>
                <view class="option-text">{{ type }}</view>
              </view>
            </view>
          </view>
          <view class="filter-section">
            <view class="filter-section-title">距离范围</view>
            <view class="filter-options">
              <view class="filter-option" v-for="(range, index) in distanceRanges" :key="index" 
                    :class="{ 'selected': selectedDistance === index }" @click="selectDistance(index)">
                <view class="option-checkbox"></view>
                <view class="option-text">{{ range }}</view>
              </view>
            </view>
          </view>
          <view class="filter-actions">
            <button class="btn-reset" @click="resetFilters">重置</button>
            <button class="btn-confirm" @click="applyFilters">确定</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 位置详情弹窗 -->
    <view class="modal-overlay" v-if="showLocationDetailModal" @click="closeLocationDetail">
      <view class="modal-content detail-modal" @click.stop>
        <view class="modal-header">
          <view class="modal-title">{{ selectedLocation.name }}</view>
          <view class="modal-close" @click="closeLocationDetail">×</view>
        </view>
        <view class="modal-body">
          <view class="detail-image">
            <image :src="selectedLocation.image" mode="aspectFill"></image>
          </view>
          <view class="detail-info">
            <view class="detail-address">
              <text class="info-label">地址：</text>
              <text class="info-value">{{ selectedLocation.address }}</text>
            </view>
            <view class="detail-phone">
              <text class="info-label">电话：</text>
              <text class="info-value">{{ selectedLocation.phone }}</text>
            </view>
            <view class="detail-hours">
              <text class="info-label">营业时间：</text>
              <text class="info-value">{{ selectedLocation.businessHours }}</text>
            </view>
            <view class="detail-capacity">
              <text class="info-label">容量状态：</text>
              <text class="info-value" :class="selectedLocation.capacityStatus === 'full' ? 'status-full' : 'status-normal'">
                {{ selectedLocation.capacityStatus === 'full' ? '已满' : '未满' }}
              </text>
            </view>
            <view class="detail-recycle-types">
              <text class="info-label">回收类型：</text>
              <text class="info-value">{{ selectedLocation.categories.join('、') }}</text>
            </view>
            <view class="detail-points">
              <text class="info-label">积分奖励：</text>
              <text class="info-value">回收+{{ selectedLocation.points }}积分</text>
            </view>
          </view>
          <view class="detail-actions">
            <button class="btn-call" @click="callRecyclePoint(selectedLocation.phone)">联系回收点</button>
            <button class="btn-navigate" @click="navigateToLocation(selectedLocation)">前往导航</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 地图相关
      latitude: 39.90923, // 默认北京坐标
      longitude: 116.397428,
      showLocation: true,
      markers: [],
      mapPoints: [],
      
      // 搜索和筛选
      searchKeyword: '',
      currentFilter: 0,
      filterCategories: [
        { icon: '', name: '全部' },
        { icon: '', name: '回收中心' },
        { icon: '', name: '社区站点' },
        { icon: '', name: '智能回收箱' }
      ],
      showFilterModal: false,
      recycleTypes: ['玻璃', '塑料', '金属'],
      selectedTypes: [],
      distanceRanges: ['1公里内', '3公里内', '5公里内', '10公里内'],
      selectedDistance: 1,
      
      // 位置数据
      locations: [
        {
          id: 1,
          name: '绿色回收中心',
          address: '北京市朝阳区建国路88号',
          latitude: 39.90923,
          longitude: 116.397428,
          distance: '0.5km',
          rating: 4.3,
          reviews: 432,
          businessHours: '08:00-18:00',
          categories: ['玻璃', '塑料', '金属'],
          points: 50,
          phone: '010-12345678',
          image: 'https://picsum.photos/seed/recycle1/300/200',
          type: '回收中心',
          capacityStatus: 'normal'
        },
        {
          id: 2,
          name: '阳光小区回收站',
          address: '北京市朝阳区三里屯路15号',
          latitude: 39.91057,
          longitude: 116.43779,
          distance: '1.2km',
          rating: 4.5,
          reviews: 287,
          businessHours: '09:00-22:00',
          categories: ['玻璃', '塑料', '金属', '纸张'],
          points: 30,
          phone: '010-87654321',
          image: 'https://picsum.photos/seed/recycle2/300/200',
          type: '社区站点',
          capacityStatus: 'full'
        },
        {
          id: 3,
          name: '智能回收箱-工体北路',
          address: '北京市朝阳区工体北路1号',
          latitude: 39.93128,
          longitude: 116.43654,
          distance: '2.1km',
          rating: 4.0,
          reviews: 156,
          businessHours: '全天24小时',
          categories: ['塑料', '纸张', '电池'],
          points: 20,
          phone: '',
          image: 'https://picsum.photos/seed/recycle3/300/200',
          type: '智能回收箱',
          capacityStatus: 'normal'
        },
        {
          id: 4,
          name: '环保驿站',
          address: '北京市朝阳区东三环中路39号',
          latitude: 39.90285,
          longitude: 116.4662,
          distance: '3.5km',
          rating: 4.2,
          reviews: 320,
          businessHours: '08:30-19:00',
          categories: ['玻璃', '塑料', '金属', '纸张', '衣物'],
          points: 45,
          phone: '010-56789012',
          image: 'https://picsum.photos/seed/recycle4/300/200',
          type: '回收中心',
          capacityStatus: 'normal'
        },
        {
          id: 5,
          name: '城市回收点',
          address: '北京市朝阳区建国路93号',
          latitude: 39.90764,
          longitude: 116.40887,
          distance: '0.8km',
          rating: 4.1,
          reviews: 210,
          businessHours: '09:00-17:00',
          categories: ['塑料', '纸张', '电池'],
          points: 25,
          phone: '010-23456789',
          image: 'https://picsum.photos/seed/recycle5/300/200',
          type: '社区站点',
          capacityStatus: 'full'
        }
      ],
      selectedLocation: null,
      showLocationDetailModal: false,
      selectedLocationName: ''
    };
  },
  
  computed: {
    filteredLocations() {
      let filtered = [...this.locations];
      
      // 搜索筛选
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        filtered = filtered.filter(loc => 
          loc.name.toLowerCase().includes(keyword) || 
          loc.address.toLowerCase().includes(keyword)
        );
      }
      
      // 类型筛选
      if (this.currentFilter > 0) {
        const filterType = this.filterCategories[this.currentFilter].name;
        filtered = filtered.filter(loc => loc.type === filterType);
      }
      
      // 回收类型筛选
      if (this.selectedTypes.length > 0) {
        filtered = filtered.filter(loc => {
          return this.selectedTypes.some(index => 
            loc.categories.includes(this.recycleTypes[index])
          );
        });
      }
      
      // 距离筛选
      const distanceLimits = [1, 3, 5, 10];
      if (this.selectedDistance >= 0 && this.selectedDistance < distanceLimits.length) {
        const maxDistance = distanceLimits[this.selectedDistance];
        filtered = filtered.filter(loc => {
          const distance = parseFloat(loc.distance);
          return distance <= maxDistance;
        });
      }
      
      return filtered;
    }
  },
  
  onLoad(options) {
    // 页面加载时获取位置权限并初始化地图
    this.initMap();
    
    // 如果有传入位置名称参数，查找并突出显示该位置
    if (options && options.locationName) {
      this.selectedLocationName = options.locationName;
      // 这里可以在数据加载后高亮显示选择的回收点
    }
  },
  
  methods: {
    // 初始化地图
    initMap() {
      // 请求定位权限
      uni.authorize({
        scope: 'scope.userLocation',
        success: () => {
          this.getLocation();
        },
        fail: () => {
          uni.showToast({
            title: '需要位置权限才能使用地图功能',
            icon: 'none'
          });
          // 使用默认位置
          this.updateMapMarkers();
        }
      });
    },
    
    // 获取当前位置
    getLocation() {
      uni.getLocation({
        type: 'gcj02',
        altitude: true,
        success: (res) => {
          this.latitude = res.latitude;
          this.longitude = res.longitude;
          this.updateMapMarkers();
          
          // 这里可以调用API获取实际的附近回收点数据
          // this.fetchNearbyLocations(res.latitude, res.longitude);
        },
        fail: (err) => {
          console.error('获取位置失败:', err);
          uni.showToast({
            title: '获取位置信息失败',
            icon: 'none'
          });
          // 使用默认位置
          this.updateMapMarkers();
        }
      });
    },
    
    // 更新地图标记
    updateMapMarkers() {
      this.markers = this.filteredLocations.map((location, index) => {
        // 检查是否是选中的回收点（使用模糊匹配）
        const isSelectedLocation = this.selectedLocationName && 
                                  location.name.includes(this.selectedLocationName) || 
                                  this.selectedLocationName.includes(location.name);
        
        // 使用现有的图标，但增加选中状态的大小和突出显示
        return {
          id: location.id,
          latitude: location.latitude,
          longitude: location.longitude,
          title: location.name,
          iconPath: '/static/icons/center_full.svg',
          width: isSelectedLocation ? 60 : 40,
          height: isSelectedLocation ? 60 : 40,
          callout: {
            content: location.name + '\n' + location.distance,
            display: isSelectedLocation ? 'ALWAYS' : 'BYCLICK',
            padding: 5,
            borderRadius: 4,
            bgColor: isSelectedLocation ? '#4CAF50' : '#ffffff',
            borderColor: '#4CAF50',
            borderWidth: 2,
            color: isSelectedLocation ? '#ffffff' : '#000000'
          }
        };
      });
      
      // 设置地图显示范围以包含所有标记
      this.mapPoints = this.filteredLocations.map(loc => ({
        latitude: loc.latitude,
        longitude: loc.longitude
      }));
    },
    
    // 切换筛选分类
    switchFilter(index) {
      this.currentFilter = index;
      this.updateMapMarkers();
    },
    
    // 显示筛选选项
    showFilterOptions() {
      this.showFilterModal = true;
    },
    
    // 关闭筛选选项
    closeFilterModal() {
      this.showFilterModal = false;
    },
    
    // 切换回收类型
    toggleType(index) {
      const idx = this.selectedTypes.indexOf(index);
      if (idx > -1) {
        this.selectedTypes.splice(idx, 1);
      } else {
        this.selectedTypes.push(index);
      }
    },
    
    // 选择距离范围
    selectDistance(index) {
      this.selectedDistance = index;
    },
    
    // 重置筛选条件
    resetFilters() {
      this.selectedTypes = [];
      this.selectedDistance = 1;
      this.currentFilter = 0;
      this.searchKeyword = '';
    },
    
    // 应用筛选条件
    applyFilters() {
      this.updateMapMarkers();
      this.closeFilterModal();
    },
    
    // 显示位置详情
    showLocationDetail(location) {
      this.selectedLocation = location;
      this.showLocationDetailModal = true;
    },
    
    // 关闭位置详情
    closeLocationDetail() {
      this.showLocationDetailModal = false;
      this.selectedLocation = null;
    },
    
    // 地图标记点击事件
    onMarkerTap(e) {
      const markerId = e.markerId;
      const location = this.locations.find(loc => loc.id === markerId);
      if (location) {
        this.showLocationDetail(location);
      }
    },
    
    // 地图标记气泡点击事件
    onCalloutTap(e) {
      const markerId = e.markerId;
      const location = this.locations.find(loc => loc.id === markerId);
      if (location) {
        this.showLocationDetail(location);
      }
    },
    
    // 拨打回收点电话
    callRecyclePoint(phone) {
      if (phone) {
        uni.makePhoneCall({
          phoneNumber: phone
        });
      } else {
        uni.showToast({
          title: '该回收点暂无联系电话',
          icon: 'none'
        });
      }
    },
    
    // 导航到回收点
    navigateToLocation(location) {
      // 调用微信地图导航API
      uni.openLocation({
        latitude: location.latitude,
        longitude: location.longitude,
        name: location.name,
        address: location.address,
        scale: 18,
        success: () => {
          console.log('导航成功');
        },
        fail: (err) => {
          console.error('导航失败:', err);
          uni.showToast({
            title: '导航失败，请重试',
            icon: 'none'
          });
        }
      });
    },
    
    // 返回上一页
    navigateBack() {
      uni.navigateBack();
    }
  },
  
  watch: {
    // 监听筛选结果变化，更新地图标记
    filteredLocations: {
      handler() {
        this.updateMapMarkers();
      },
      deep: true
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 导航栏样式 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  background-color: #4CAF50;
  color: #ffffff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
}

.nav-back, .nav-location {
  font-size: 32rpx;
}

/* 搜索框样式 */
.search-bar {
  padding: 20rpx 30rpx;
  background-color: #ffffff;
}

.search-input {
  width: 100%;
  height: 80rpx;
  padding: 0 30rpx;
  background-color: #f0f0f0;
  border-radius: 40rpx;
  font-size: 30rpx;
}

/* 筛选标签样式 */
.filter-tabs {
  background-color: #ffffff;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.filter-scroll {
  white-space: nowrap;
  padding: 0 30rpx;
}

.filter-tab {
  display: inline-block;
  padding: 15rpx 30rpx;
  margin-right: 20rpx;
  border-radius: 40rpx;
  background-color: #f0f0f0;
  color: #666666;
  font-size: 28rpx;
}

.filter-tab.active {
  background-color: #4CAF50;
  color: #ffffff;
}

/* 地图容器样式 */
.map-container {
  width: 100%;
  height: 500rpx;
  background-color: #ffffff;
  margin-bottom: 20rpx;
}

.map {
  width: 100%;
  height: 100%;
}

/* 回收点列表样式 */
.location-list {
  background-color: #ffffff;
  padding: 20rpx 30rpx;
}

.list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.list-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.list-filter {
  font-size: 28rpx;
  color: #666666;
}

.location-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eeeeee;
  position: relative;
}

.location-item:last-child {
  border-bottom: none;
}

.location-img {
  width: 180rpx;
  height: 180rpx;
  border-radius: 10rpx;
  overflow: hidden;
  margin-right: 20rpx;
  float: left;
}

.location-img image {
  width: 100%;
  height: 100%;
}

.location-info {
  overflow: hidden;
  padding-right: 200rpx;
}

.location-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 10rpx;
}

.location-category {
  margin-bottom: 10rpx;
}

.category-tag {
  display: inline-block;
  padding: 5rpx 15rpx;
  background-color: #e8f5e9;
  color: #4CAF50;
  font-size: 24rpx;
  border-radius: 15rpx;
  margin-right: 10rpx;
}

.location-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
  font-size: 26rpx;
  color: #666666;
}

.location-ratings {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.star-icon {
  font-size: 24rpx;
  color: #dddddd;
  margin-right: 5rpx;
}

.star-icon.filled {
  color: #FFD700;
}

.rating-text {
  font-size: 26rpx;
  color: #333333;
  font-weight: bold;
  margin-left: 10rpx;
}

.review-count {
  font-size: 24rpx;
  color: #999999;
  margin-left: 10rpx;
}

.location-hours {
  font-size: 26rpx;
  color: #666666;
}

.location-actions {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
}

.btn-call, .btn-navigate {
  width: 160rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  border-radius: 30rpx;
  font-size: 26rpx;
  margin-bottom: 10rpx;
  padding: 0;
}

.btn-call {
  background-color: #e3f2fd;
  color: #2196F3;
  border: none;
}

.btn-navigate {
  background-color: #4CAF50;
  color: #ffffff;
  border: none;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.modal-content {
  background-color: #ffffff;
  border-radius: 20rpx;
  width: 90%;
  max-height: 80vh;
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #eeeeee;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
}

.modal-close {
  font-size: 48rpx;
  color: #999999;
  line-height: 1;
}

.modal-body {
  padding: 30rpx;
}

/* 筛选弹窗样式 */
.filter-modal {
  width: 95%;
}

.filter-section {
  margin-bottom: 30rpx;
}

.filter-section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 20rpx;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
}

.filter-option {
  display: flex;
  align-items: center;
  padding: 15rpx 25rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 40rpx;
  background-color: #f0f0f0;
  color: #666666;
  font-size: 28rpx;
}

.filter-option.selected {
  background-color: #e8f5e9;
  color: #4CAF50;
  border: 1rpx solid #4CAF50;
}

.option-checkbox {
  width: 30rpx;
  height: 30rpx;
  border: 2rpx solid #cccccc;
  border-radius: 50%;
  margin-right: 10rpx;
  position: relative;
}

.filter-option.selected .option-checkbox {
  border-color: #4CAF50;
  background-color: #4CAF50;
}

.filter-option.selected .option-checkbox::after {
  content: '✓';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #ffffff;
  font-size: 20rpx;
  font-weight: bold;
}

.filter-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 40rpx;
}

.btn-reset, .btn-confirm {
  flex: 1;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  border-radius: 45rpx;
  font-size: 32rpx;
  margin: 0 10rpx;
  padding: 0;
}

.btn-reset {
  background-color: #f0f0f0;
  color: #666666;
  border: none;
}

.btn-confirm {
  background-color: #4CAF50;
  color: #ffffff;
  border: none;
}

/* 详情弹窗样式 */
.detail-modal {
  width: 95%;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.detail-image {
  width: 100%;
  height: 300rpx;
  border-radius: 10rpx;
  overflow: hidden;
  margin-bottom: 30rpx;
}

.detail-image image {
  width: 100%;
  height: 100%;
}

.detail-info {
  margin-bottom: 30rpx;
}

.detail-address, .detail-phone, .detail-hours, .detail-capacity, .detail-recycle-types, .detail-points {
  margin-bottom: 20rpx;
  font-size: 28rpx;
  color: #333333;
}

.info-label {
  color: #666666;
  margin-right: 20rpx;
}

.info-value.status-full {
  color: #f44336;
}

.info-value.status-normal {
  color: #4CAF50;
}

.detail-actions {
  display: flex;
  justify-content: space-between;
}

.detail-actions .btn-call, .detail-actions .btn-navigate {
  flex: 1;
  margin: 0 10rpx;
}
</style>